package com.hundsun.fcp.webplugin.javascript;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.hundsun.fcp.common.Redirect;
import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebView;

public class WebHtmlProxy {

	private static final Logger LOGGER = AndroidLogger.getLogger();
	private Handler mHandler = new Handler();
	private WebView mWebView;

	public WebHtmlProxy(WebView pWebView) {
		mWebView = pWebView;
	}
	
	/**
	 * 添加银行卡
	 */
	public void addBank(){
		Redirect.startBankAdd(mWebView.getContext()) ;
	}

	/**
	 * webview 加载 url
	 * @param url
	 */
	private void loadUrlInWebView(final String url) {
		this.mHandler.post(new Runnable() {
			public void run() {
				mWebView.loadUrl(url);
			}
		});
	}
	
	@JavascriptInterface
	public void webEvent(String function,String args){
		LOGGER.debug(String.format("webEvent(%s, %s)",function, args)) ;
		try{
			
			if(WebEventFunction.BACK.equals(function)){//返回操作
				mHandler.post(new Runnable() {
					
					@Override
					public void run() {
						if(mWebView instanceof FcpWebView){
							((FcpWebView)mWebView).clearLocalStorage() ;
						}
						
						if(mWebView.canGoBack()){
							mWebView.goBack();
						}else{
							 Context _Context = mWebView.getContext() ;
							 if(_Context instanceof Activity){
								 ((Activity)_Context).finish() ;
							 }
						}
							
					}
				});
			}else if(WebEventFunction.QUIT.equals(function)){ //退出操作
				 Context _Context = mWebView.getContext() ;
				 if(_Context instanceof Activity){
					 ((Activity)_Context).finish() ;
				 }
			}
			
		}catch(Exception e){
			LOGGER.error("webEvent 处理异常", e) ;
		}
		
	}

}
